package com.yicong.ants.manager.config;

import android.content.Context;
import android.os.Build;
import android.view.View;

import androidx.fragment.app.FragmentActivity;

import com.blankj.utilcode.util.StringUtils;
import com.cchao.simplelib.Const;
import com.cchao.simplelib.core.JsonHelper;
import com.cchao.simplelib.core.Logs;
import com.cchao.simplelib.core.PrefHelper;
import com.cchao.simplelib.core.Router;
import com.cchao.simplelib.core.RxHelper;
import com.cchao.simplelib.core.UiHelper;
import com.cchao.simplelib.ui.activity.BaseActivity;
import com.cchao.simplelib.ui.web.WebViewActivity;
import com.cchao.simplelib.util.StringHelper;
import com.cchao.simplelib.util.UrlUtil;
import com.yicong.ants.BuildConfig;
import com.yicong.ants.Constants;
import com.yicong.ants.R;
import com.yicong.ants.bean.account.UserBean;
import com.yicong.ants.bean.global.ClientConfig;
import com.yicong.ants.bean.home.IndexConfig;
import com.yicong.ants.manager.BusinessHelper;
import com.yicong.ants.manager.UserManager;
import com.yicong.ants.manager.http.RetrofitHelper;
import com.yicong.ants.scenic.ScenicMainActivity;
import com.yicong.ants.ui.find.YcWebViewActivity;
import com.yicong.ants.ui.me.MeAntFragment;
import com.yicong.ants.ui.scenic.ScenicListActivity;
import com.yicong.ants.ui.scenic.TourismConfigFragment;
import com.yicong.ants.ui.video.VideoMainFragment;
import com.yicong.ants.utils.AmapHelper;
import com.yicong.ants.utils.InitUtil;

import org.apache.commons.lang3.tuple.Triple;

import java.util.HashMap;
import java.util.Map;

/**
 * 配置子类
 *
 * @author cchao
 * @version 2019-07-03.
 */
public class ZzConfigs extends ConfigParent {
    public static final String Ant_App_Id = "com.yicong.ants";
    public static IndexConfig mIndexInfo;

    public static void init() {
        MainConfig.init();
        // 拉取上一次的 config
        try {
            String configStr = PrefHelper.getString(Constants.Prefs.Index_Info, "");
            if (StringHelper.isNotEmpty(configStr)) {
                mIndexInfo = JsonHelper.toObject(configStr, IndexConfig.class);
            }

            if (mIndexInfo == null) {
                mIndexInfo = new IndexConfig();
            }
        } catch (Exception ex) {
            Logs.logException(ex);
        }
    }

    public static void updateIndexConfig(IndexConfig data) {
        ZzConfigs.mIndexInfo = data;
        PrefHelper.putString(Constants.Prefs.Index_Info, JsonHelper.toJson(ZzConfigs.mIndexInfo));
    }

    public static ClientConfig getClientConf() {
        if (StringHelper.isEmpty(PrefHelper.getString(Constants.Prefs.Index_Info, "")) && InitUtil.INSTANCE.isInit()) {
            BusinessHelper.loadIndexConfig(null);
        }
        if (mIndexInfo == null) {
            mIndexInfo = new IndexConfig();
        }
        return mIndexInfo.getConfig();
    }

    public static String getProductHost() {
        return Constants.Api_Product;
    }

    public static String getApi() {
        if (StringHelper.isNotEmpty(PrefHelper.getString(Constants.Prefs.Dev_Api))) {
            return PrefHelper.getString(Constants.Prefs.Dev_Api);
        }
        return getProductHost();
    }

    /**
     * 从 clientConfig 里面获取的 webUrl 跳转
     */
    public static void toWebActivityByUrl(Context context, String key) {
        ClientConfig.WebUrl webUrl = getWebUrl(key);

        Router.turnTo(context, YcWebViewActivity.class)
                .putExtra(Const.Extra.Web_View_Url, webUrl.getUrl())
                .putExtra(Const.Extra.Web_View_Tile, webUrl.getTitle())
                .putExtra(Const.Extra.Web_View_Title_Visible, StringHelper.isNotEmpty(webUrl.getTitle()))
                .checkLogin(true)
                .start();
    }

    public static void toWebActivityByUrlNoTitle(Context context, String key) {
        ClientConfig.WebUrl webUrl = getWebUrl(key);

        Router.turnTo(context, YcWebViewActivity.class)
                .putExtra(Const.Extra.Web_View_Url, webUrl.getUrl())
                .putExtra(Const.Extra.Web_View_Tile, webUrl.getTitle())
                .putExtra(Const.Extra.Web_View_Title_Visible, false)
                .checkLogin(true)
                .start();
    }

    public static void toWebActivityByUrl(Context context, String key, String p) {
        ClientConfig.WebUrl webUrl = getWebUrl(key);

        Router.turnTo(context, YcWebViewActivity.class)
                .putExtra(Const.Extra.Web_View_Url, webUrl.getUrl() + p)
                .putExtra(Const.Extra.Web_View_Tile, webUrl.getTitle())
                .putExtra(Const.Extra.Web_View_Title_Visible, StringHelper.isNotEmpty(webUrl.getTitle()))
                .checkLogin(true)
                .start();
    }

    /**
     * 从 clientConfig 里面获取的 webUrl 跳转
     */
    public static void toWebActivityByUrlNoLogin(Context context, String key) {
        ClientConfig.WebUrl webUrl = getWebUrl(key);

        Router.turnTo(context, YcWebViewActivity.class)
                .putExtra(Const.Extra.Web_View_Url, webUrl.getUrl())
                .putExtra(Const.Extra.Web_View_Tile, webUrl.getTitle())
                .putExtra(Const.Extra.Web_View_Title_Visible, StringHelper.isNotEmpty(webUrl.getTitle()))
                .start();
    }

    public static void onLoadApi(Context context, int type, String webTitle) {
        if (UserManager.notLogin()) {
            UserManager.routeLogin(context);
            return;
        }
        if (!(context instanceof BaseActivity)) {
            return;
        }
        BaseActivity activity = (BaseActivity) context;
        activity.showProgress();
        Map<String, String> map = new HashMap<>(4);
        map.put("type", String.valueOf(type));
        activity.addSubscribe(RetrofitHelper.getApis().getThirdService(map)
                .compose(RxHelper.toMain())
                .subscribe(respBean -> {
                    activity.hideProgress();
                    if (respBean.isCodeFail()) {
                        activity.showToast(respBean.getMsg());
                        return;
                    }
                    toWebActivity(context, webTitle, respBean.getData().get("url"));
                }, RxHelper.getHideProgressConsumer(activity)));
    }

    public static String wrapUrlParam(String url) {
        HashMap<String, String> map = new HashMap<>();
        map.put("platform", "2");
        map.put("phoneModel", Build.MODEL);
        map.put("app_id", BuildConfig.APPLICATION_ID);
        map.put("android_version_code", String.valueOf(BuildConfig.VERSION_CODE));
        // 有定位信息
        if (AmapHelper.mAMapLocation != null) {
            map.put("latitude", String.valueOf(AmapHelper.mAMapLocation.getLatitude()));
            map.put("longitude", String.valueOf(AmapHelper.mAMapLocation.getLongitude()));
        }
        // 已登录
        if (UserManager.isLogin()) {
            UserBean userBean = UserManager.getUserBean();
            map.put("uid", userBean.getId());
            map.put("mobile", userBean.getMobile());
        }
        return UrlUtil.appendParameter(url, map);
    }

    public static String wrapUrlParamToken(String url) {
        HashMap<String, String> map = new HashMap<>();
        map.put("platform", "2");
        map.put("phoneModel", Build.MODEL);
        map.put("app_id", BuildConfig.APPLICATION_ID);
        map.put("android_version_code", String.valueOf(BuildConfig.VERSION_CODE));
        // 已登录
        if (UserManager.isLogin()) {
            map.put("token", UserManager.getUserBean().getJwt_token());
        }
        return UrlUtil.appendParameter(url, map);
    }

    public static String wrapLineUrlToken(String url) {
        // 已登录
        if (UserManager.isLogin()) {
            if (url.contains("?")) {
                return url + "&token=" + UserManager.getUserBean().getJwt_token();
            }
            return url + "?token=" + UserManager.getUserBean().getJwt_token();
        }
        return url;
    }

    public static void toWebActivity(Context context, String webTitle, String url) {
        Logs.logEvent("toWebActivity title: " + webTitle + " url " + url);
        // 加载网页
        Router.turnTo(context, YcWebViewActivity.class)
                .putExtra(Const.Extra.Web_View_Url, url)
                .putExtra(Const.Extra.Web_View_Tile, webTitle)
                .putExtra(Const.Extra.Web_View_Title_Visible, !StringUtils.isEmpty(webTitle))
                .start();
    }

    /**
     * 从 clientConfig 里面获取的 webUrl 跳转
     */
    public static void toWebActivityByUrlNotLogin(Context context, String key) {
        ClientConfig.WebUrl webUrl = getWebUrl(key);

        Router.turnTo(context, YcWebViewActivity.class)
                .putExtra(Const.Extra.Web_View_Url, webUrl.getUrl())
                .putExtra(Const.Extra.Web_View_Tile, webUrl.getTitle())
                .putExtra(Const.Extra.Web_View_Title_Visible, StringHelper.isNotEmpty(webUrl.getTitle()))
                .start();
    }


    /**
     * @param context context
     * @param key     从 clientConfig 里面获取的 webUrl 跳转
     * @param visible true 显示title
     */
    public static void toWebActivityByUrlTitleState(Context context, String key, boolean visible) {
        ClientConfig.WebUrl webUrl = getWebUrl(key);
        Router.turnTo(context, YcWebViewActivity.class)
                .putExtra(Const.Extra.Web_View_Url, webUrl.getUrl())
                .putExtra(Const.Extra.Web_View_Tile, webUrl.getTitle())
                .putExtra(Const.Extra.Web_View_Title_Visible, visible)
                .start();
    }

    public static ClientConfig.WebUrl getWebUrl(String key) {
        Map<String, ClientConfig.WebUrl> webUrl = ZzConfigs.getClientConf().getWeb_url();
        if (webUrl == null) {
            BusinessHelper.loadIndexConfig(null);
            UiHelper.showToast("加载页面失败，请重启 App 后再试");
            return new ClientConfig.WebUrl();
        }

        for (Map.Entry<String, ClientConfig.WebUrl> entry : webUrl.entrySet()) {
            if (entry.getKey().equalsIgnoreCase(key)) {
                return entry.getValue();
            }
        }
        return new ClientConfig.WebUrl();
    }

    public static class MainConfig {
        public static void init() {
            // tourism
            mTourismSearchBar = true;
            mTourismPortalGridNum = 5;
            mTourismScenicStyle = R.layout.tourism_rec_item;
//            mScenicShowAddedItems = View.VISIBLE;
            initTourismPortal();
            mScenicShowPriceVisible = View.VISIBLE;

            // global
            mGlobalApi = getApi();
            mGlobalStartGuideAble = false;
            mGlobalCollectFeature = true;

            // home
            initMainFragment();

            // mine
            mMineSignAble = false;
        }

        private static void initTourismPortal() {
            mTourismPortal.clear();
            if (getClientConf().isNewYear()) {
// 1.预约景区，2.免约景区，3.特惠景区，4.游玩记录，5.我的推荐，6.推荐好友，7.会员信息（我的旅游卡），8.我的订单（购买记录）
//            mTourismPortal.add(Triple.of(R.drawable.tourism_entry_scenic, "预约景区"
//                , toScenicListAty(Constants.Scenic_Type.AppointScenic)));
                mTourismPortal.add(Triple.of(R.mipmap.icon_home_scenic_1, "景区"
                        , context -> {
                            //
//                            Router.turnTo(context, ScenicTabActivity.class).start();
                        }));

//            mTourismPortal.add(Triple.of(R.drawable.travel_item_2, "预约景区"
//                , toScenicListAty(Constants.Scenic_Type.SetPartnerAdvance)));

                if (!BuildConfig.STORE) {
                    mTourismPortal.add(Triple.of(R.mipmap.icon_home_hotel_1
                            , "酒店", context -> {
                                toWebActivityByUrl(context, "hotel");
                            }));

                    mTourismPortal.add(Triple.of(R.mipmap.icon_home_travel_1
                            , "出行", context -> {
                                toWebActivityByUrl(context, "traffic");
                            }));
                }

                mTourismPortal.add(Triple.of(R.mipmap.icon_home_line_1
                        , "旅游线路", context -> {

                            toWebActivityByUrl(context, "travel_line");
                        }));

                mTourismPortal.add(Triple.of(R.mipmap.icon_home_shoppingmall_1
                        , "蚁丛商城", context -> {
                            toWebActivityByUrl(context, "mall");
                        }));

                mTourismPortal.add(Triple.of(R.mipmap.icon_home_business_1,
                        "合作商家", context -> {
                            toWebActivityByUrlNoLogin(context, "merchants");
                        }));

                if (!BuildConfig.STORE) {
                    mTourismPortal.add(Triple.of(R.mipmap.icon_home_bill_1
                            , "生活缴费", context -> {
                                toWebActivityByUrl(context, "recharge");
                            }));
                }

                if (!BuildConfig.STORE) {
                    mTourismPortal.add(Triple.of(R.mipmap.icon_home_prettynumber_1
                            , "靓号广场", context -> {
                                ZzConfigs.toWebActivityByUrl(context, "project_nice_number");
                            }));
                }

                if (!BuildConfig.STORE) {
                    mTourismPortal.add(Triple.of(R.mipmap.icon_home_game_1
                            , "游戏中心", context -> {
                                //
                                toWebActivityByUrl(context, "sdw_game");
                            }));
                }

                if (!BuildConfig.STORE) {
                    mTourismPortal.add(Triple.of(R.mipmap.icon_home_expect_1
                            , "敬请期待", context -> {
                            }));
                }
            } else {
                // 1.预约景区，2.免约景区，3.特惠景区，4.游玩记录，5.我的推荐，6.推荐好友，7.会员信息（我的旅游卡），8.我的订单（购买记录）
//            mTourismPortal.add(Triple.of(R.drawable.tourism_entry_scenic, "预约景区"
//                , toScenicListAty(Constants.Scenic_Type.AppointScenic)));
                mTourismPortal.add(Triple.of(R.drawable.travel_item_1, "景区"
                        , context -> {
                            //
                            Router.turnTo(context, ScenicMainActivity.class).start();
                        }));

//            mTourismPortal.add(Triple.of(R.drawable.travel_item_2, "预约景区"
//                , toScenicListAty(Constants.Scenic_Type.SetPartnerAdvance)));

                if (!BuildConfig.STORE) {
                    mTourismPortal.add(Triple.of(R.drawable.travel_item_5
                            , "酒店", context -> {
                                toWebActivityByUrl(context, "hotel");
                            }));

                    mTourismPortal.add(Triple.of(R.drawable.travel_item_tra
                            , "出行", context -> {
                                toWebActivityByUrl(context, "traffic");
                            }));
                }

                mTourismPortal.add(Triple.of(R.drawable.travel_item_4
                        , "旅游线路", context -> {

                            toWebActivityByUrl(context, "travel_line");
                        }));

                mTourismPortal.add(Triple.of(R.drawable.travel_item_6
                        , "蚁丛商城", context -> {
                            toWebActivityByUrl(context, "mall");
                        }));

                mTourismPortal.add(Triple.of(R.drawable.travel_item_3,
                        "合作商家", context -> {
                            toWebActivityByUrlNoLogin(context, "merchants");
                        }));

                if (!BuildConfig.STORE) {
                    mTourismPortal.add(Triple.of(R.drawable.fee_charge
                            , "生活缴费", context -> {
                                toWebActivityByUrl(context, "recharge");
                            }));
                }

                if (!BuildConfig.STORE) {
                    mTourismPortal.add(Triple.of(R.drawable.travel_item_liang
                            , "靓号广场", context -> {
                                ZzConfigs.toWebActivityByUrl(context, "project_nice_number");
                            }));
                }

                if (!BuildConfig.STORE) {
                    mTourismPortal.add(Triple.of(R.drawable.travel_item_game
                            , "游戏中心", context -> {
                                //
                                toWebActivityByUrl(context, "sdw_game");
                            }));
                }

                if (!BuildConfig.STORE) {
                    mTourismPortal.add(Triple.of(R.drawable.travel_item_working
                            , "敬请期待", context -> {
                            }));
                }
            }
        }

        private static void initMainFragment() {
            mHomeFragment.clear();
            if (getClientConf().isNewYear()) {
                mHomeFragment.add(Triple.of(R.drawable.main_tab_yicong_a, "首页", new TourismConfigFragment()));
                if (!BuildConfig.STORE) {
                    mHomeFragment.add(Triple.of(R.drawable.home_tab_vedio_c, "视频", new VideoMainFragment()));
                }
                mHomeFragment.add(Triple.of(R.drawable.main_tab_yicong_b, "我的", new MeAntFragment()));
            } else {
                mHomeFragment.add(Triple.of(R.drawable.main_tab1_yicong, "首页", new TourismConfigFragment()));
                if (!BuildConfig.STORE) {
                    mHomeFragment.add(Triple.of(R.drawable.home_tab4_vedio, "视频", new VideoMainFragment()));
                }
                mHomeFragment.add(Triple.of(R.drawable.main_tab2_yicong, "我的", new MeAntFragment()));
            }
        }
    }

    public static void toWebActivityCheckLogin(Context context, String webTitle, String url) {
        // 加载网页
        Router.turnTo(context, YcWebViewActivity.class)
                .putExtra(Const.Extra.Web_View_Url, url)
                .putExtra(Const.Extra.Web_View_Tile, webTitle)
                .checkLogin(true)
                .start();
    }

    public static void toWebActivityToken(Context context, String webTitle, String url) {
        // 加载网页
        Router.turnTo(context, WebViewActivity.class)
                .putExtra(Const.Extra.Web_View_Url, wrapUrlParamToken(url))
                .putExtra(Const.Extra.Web_View_Tile, webTitle)
                .checkLogin(true)
                .start();
    }

    //    景区类型[10=特惠景区，20=预约景区，30=免预约景区，100=免费景区（免预约和预约的合集）]
    static RouterCallback toScenicListAty(String i) {
        return context -> {
            if (context instanceof FragmentActivity &&
                    !BusinessHelper.checkPermission((FragmentActivity) context)) {
                return;
            }

            Router.turnTo(context, ScenicListActivity.class)
                    .putExtra(Constants.Extra.Scenic_Type, i)
                    .start();
        };
    }
}
